<template>
  <div class="device-data-product">
    <TableHeader>
      <template #headerTop>
        <div class="flex">
          <div class="flex-1">
            <!-- 删除类型切换 Segmented，保留空白占位 -->
          </div>
          <Space :size="1" class="mx-4">
            <Tooltip :title="t('tb.dataProduct.actions.add')">
              <Icon icon="ant-design:plus-outlined" :size="20" class="cursor-pointer" @click="handleAdd" />
            </Tooltip>
            <Tooltip :title="t('tb.dataProduct.actions.refresh')">
              <Icon icon="ant-design:redo-outlined" :size="20" class="cursor-pointer" @click="fetchDataProducts" />
            </Tooltip>
            <Tooltip :title="t('tb.dataProduct.actions.search')">
              <Icon
                icon="ant-design:search-outlined"
                :size="20"
                class="cursor-pointer"
                @click="() => (showSearch = !showSearch)"
              />
            </Tooltip>
            <Tooltip :title="t('tb.dataProduct.actions.batchDelete')">
              <Icon
                icon="ant-design:delete-outlined"
                :size="20"
                :class="[
                  'cursor-pointer',
                  selectedRowKeys.length === 0 ? 'text-gray-300 cursor-not-allowed' : 'text-red-500',
                ]"
                @click="selectedRowKeys.length > 0 && handleBatchDelete()"
              />
            </Tooltip>
            <template #split>
              <Divider type="vertical" />
            </template>
          </Space>
        </div>
      </template>
    </TableHeader>

    <div v-if="showSearch" class="mb-4">
      <Input
        v-model:value="searchKeyword"
        :placeholder="t('tb.dataProduct.searchPlaceholder')"
        allow-clear
        @change="handleSearch"
      >
        <template #prefix>
          <Icon icon="ant-design:search-outlined" />
        </template>
      </Input>
    </div>

    <BasicTable @register="registerTable" :loading="loading" :dataSource="filteredDataSource">
      <template #dataSubjectColumn="{ record }">
        <Tag v-if="record.dataSubject == 0" color="blue">{{ t('tb.dataProduct.types.individual') }}</Tag>
        <Tag v-else-if="record.dataSubject == 1" color="green">{{ t('tb.dataProduct.types.enterprise') }}</Tag>
        <Tag v-else-if="record.dataSubject == 2" color="orange">{{ t('tb.dataProduct.types.public') }}</Tag>
        <Tag v-else>{{ record.dataSubject }}</Tag>
      </template>
      <template #payMethodColumn="{ record }">
        <span v-if="record.payMethod == 0">{{ t('tb.dataProduct.payMethods.monthly') }}</span>
        <span v-else-if="record.payMethod == 1">{{ t('tb.dataProduct.payMethods.quarterly') }}</span>
        <span v-else-if="record.payMethod == 2">{{ t('tb.dataProduct.payMethods.yearly') }}</span>
        <span v-else>{{ record.payMethod }}</span>
      </template>
      <template #resourceIdColumn="{ record }">
        <span v-if="record.resourceId && record.resourceId.length > 0">
          {{ t('tb.dataProduct.resourceSelected', { count: record.resourceId.length }) }}
        </span>
        <span v-else>--</span>
      </template>
    </BasicTable>

    <CreateOrEditDataProductModal @register="registerModal" @success="handleSuccess" />
  </div>
</template>

<script lang="ts" setup>
  import { ref, computed, onMounted } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Icon } from '/@/components/Icon';
  import { Space, Divider, Tooltip, Input, Tag } from 'ant-design-vue';
  import { BasicTable, BasicColumn, useTable, TableHeader } from '/@/components/Table';
  import { useModal } from '/@/components/Modal';
  import {
    fetchDataProducts as fetchDataProductsApi,
    deleteDataProducts,
    toggleDataProductStatus,
    type ServiceDataProduct,
  } from '/@/api/service/dataSource';
  import CreateOrEditDataProductModal from './CreateOrEditDataProductModal.vue';

  const props = defineProps<{
    deviceId?: string;
  }>();

  const { t } = useI18n();
  const { createConfirm, showMessage } = useMessage();

  const loading = ref(false);
  const dataSource = ref<ServiceDataProduct[]>([]);
  const showSearch = ref(false);
  const searchKeyword = ref('');
  const selectedRowKeys = ref<string[]>([]);

  const tableColumns: BasicColumn[] = [
    {
      title: t('tb.dataProduct.columns.productName'),
      dataIndex: 'productName',
      width: 180,
      align: 'center',
    },
    {
      title: t('tb.dataProduct.columns.industry'),
      dataIndex: 'industry',
      width: 120,
      align: 'center',
    },
    {
      title: t('tb.dataProduct.columns.dataSize'),
      dataIndex: 'dataSize',
      width: 120,
      align: 'center',
    },
    {
      title: t('tb.dataProduct.columns.description'),
      dataIndex: 'description',
      width: 200,
      align: 'center',
    },
    {
      title: t('tb.dataProduct.columns.dataSubject'),
      dataIndex: 'dataSubject',
      width: 140,
      align: 'center',
      slots: { customRender: 'dataSubjectColumn' },
    },
    {
      title: t('tb.dataProduct.columns.providerName'),
      dataIndex: 'providerName',
      width: 150,
      align: 'center',
    },
    {
      title: t('tb.dataProduct.columns.identityId'),
      dataIndex: 'identityId',
      width: 180,
      align: 'center',
    },
    {
      title: t('tb.dataProduct.columns.payMethod'),
      dataIndex: 'payMethod',
      width: 120,
      align: 'center',
      slots: { customRender: 'payMethodColumn' },
    },
    {
      title: t('tb.dataProduct.columns.resourceId'),
      dataIndex: 'resourceId',
      width: 150,
      align: 'center',
      slots: { customRender: 'resourceIdColumn' },
    },
  ];

  const actionColumn: BasicColumn = {
    width: 240,
    actions: (record: Recordable) => {
      const product = record as ServiceDataProduct;
      const isEnabled = product.enabled == 1 || product.enabled === '1';

      return [
        {
          label: t('tb.dataProduct.actions.edit'),
          onClick: handleEdit.bind(null, product),
        },
        {
          label: isEnabled ? t('tb.dataProduct.actions.disable') : t('tb.dataProduct.actions.enable'),
          onClick: handleToggleStatus.bind(null, product),
        },
        {
          label: t('tb.dataProduct.actions.delete'),
          color: 'error',
          onClick: handleDelete.bind(null, product),
        },
      ];
    },
  };

  const [registerModal, { openModal }] = useModal();
  const [registerTable] = useTable({
    rowKey: 'productName',
    columns: tableColumns,
    actionColumn: actionColumn,
    showTableSetting: false,
    useSearchForm: false,
    canResize: true,
    scroll: { y: 520 },
    pagination: false,
    striped: false, // 禁用斑马纹
    rowSelection: {
      type: 'checkbox',
      onChange: (keys: string[]) => {
        selectedRowKeys.value = keys as string[];
      },
    },
  });

  const filteredDataSource = computed(() => {
    let result = [...dataSource.value];

    if (searchKeyword.value) {
      const keyword = searchKeyword.value.toLowerCase();
      result = result.filter(
        (item) =>
          item.productName?.toLowerCase().includes(keyword) ||
          item.description?.toLowerCase().includes(keyword) ||
          item.providerName?.toLowerCase().includes(keyword),
      );
    }

    return result;
  });

  onMounted(() => {
    fetchDataProducts();
  });

  async function fetchDataProducts() {
    try {
      loading.value = true;
      const response = await fetchDataProductsApi(props.deviceId || '');
      if (response && response.data) {
        if (Array.isArray(response.data)) {
          dataSource.value = response.data;
        } else if (typeof response.data === 'object' && Object.keys(response.data).length === 0) {
          dataSource.value = [];
        } else {
          dataSource.value = []
        }
      } else {
        dataSource.value = [];
      }
    } catch (error: any) {
      console.error('获取数据产品列表失败:', error);
      showMessage(t('tb.dataProduct.messages.fetchError'), 'error');
      dataSource.value = [];
    } finally {
      loading.value = false;
    }
  }

  function handleSearch() {
    // 搜索由 computed 自动处理
  }

  function handleAdd() {
    openModal(true, {
      isUpdate: false,
      deviceId: props.deviceId,
    });
  }

  function handleEdit(record: ServiceDataProduct) {
    openModal(true, {
      isUpdate: true,
      record,
      deviceId: props.deviceId,
    });
  }

  function handleDelete(record: ServiceDataProduct) {
    createConfirm({
      iconType: 'warning',
      title: t('tb.dataProduct.actions.deleteConfirm'),
      content: `${t('tb.dataProduct.columns.productName')}: ${record.productName}`,
      centered: false,
      okText: t('tb.dataProduct.actions.delete'),
      okButtonProps: {
        type: 'primary',
        danger: true,
      },
      onOk: async () => {
        try {
          await deleteDataProducts(props.deviceId || '', record['.name']);
          showMessage(t('tb.dataProduct.messages.deleteSuccess'), 'success');
          await fetchDataProducts();
        } catch (error: any) {
          console.error('删除数据产品失败:', error);
          showMessage('删除数据产品失败', 'error');
        }
      },
    });
  }

  function handleBatchDelete() {
    if (selectedRowKeys.value.length === 0) {
      return;
    }

    const selectedRecords = dataSource.value.filter((item) => selectedRowKeys.value.includes(item.productName));
    const names = selectedRecords.map((r) => r['.name']).join(',');

    createConfirm({
      iconType: 'warning',
      title: t('tb.dataProduct.actions.batchDeleteConfirm'),
      content: `${t('tb.dataProduct.selectedCount')}: ${selectedRowKeys.value.length}`,
      centered: false,
      okText: t('tb.dataProduct.actions.batchDelete'),
      okButtonProps: {
        type: 'primary',
        danger: true,
      },
      onOk: async () => {
        try {
          await deleteDataProducts(props.deviceId || '', names);
          showMessage(t('tb.dataProduct.messages.batchDeleteSuccess'), 'success');
          selectedRowKeys.value = [];
          await fetchDataProducts();
        } catch (error: any) {
          console.error('批量删除失败:', error);
          showMessage('批量删除失败', 'error');
        }
      },
    });
  }

  function handleToggleStatus(record: ServiceDataProduct) {
    const isEnabled = record.enabled == 1 || record.enabled === '1';
    const action = isEnabled ? 'disable' : 'enable';
    const title = isEnabled
      ? t('tb.dataProduct.actions.disableConfirm')
      : t('tb.dataProduct.actions.enableConfirm');

    createConfirm({
      iconType: 'warning',
      title,
      content: `${t('tb.dataProduct.columns.productName')}: ${record.productName}`,
      centered: false,
      okText: isEnabled ? t('tb.dataProduct.actions.disable') : t('tb.dataProduct.actions.enable'),
      onOk: async () => {
        try {
          await toggleDataProductStatus(props.deviceId || '', record['.name'], action);
          showMessage(
            isEnabled ? t('tb.dataProduct.messages.disableSuccess') : t('tb.dataProduct.messages.enableSuccess'),
            'success',
          );
          await fetchDataProducts();
        } catch (error: any) {
          console.error('切换状态失败:', error);
          showMessage('切换状态失败', 'error');
        }
      },
    });
  }

  function handleSuccess() {
    fetchDataProducts();
  }
</script>

<style lang="less" scoped>
  .device-data-product {
    // 保持与数据源信息页签一致的样式
  }
</style>
